#include "bridgeconfigdialog.h"
#include <QMessageBox>
#include <QRegularExpression>
#include <QHostAddress>

// 工具函数：判断两个IP/掩码是否同网段
static bool isSameSubnet(const QString& ip1, const QString& mask1, const QString& ip2, const QString& mask2) {
    QHostAddress addr1(ip1), addr2(ip2), m1(mask1), m2(mask2);
    if (addr1.isNull() || addr2.isNull() || m1.isNull() || m2.isNull()) return false;
    quint32 net1 = addr1.toIPv4Address() & m1.toIPv4Address();
    quint32 net2 = addr2.toIPv4Address() & m2.toIPv4Address();
    return net1 == net2;
}

BridgeConfigDialog::BridgeConfigDialog(const QList<ConnectionInfo>& candidates, QWidget *parent, const QString& bridgeIp, const QString& bridgeMask)
    : QDialog(parent), ui(), m_candidates(candidates), m_bridgeIp(bridgeIp), m_bridgeMask(bridgeMask)
{
    ui.setupUi(this);
    ui.listWidgetDevices->setSelectionMode(QAbstractItemView::NoSelection); // 只用复选框
    setWindowTitle("配置网卡桥接");
    setModal(true);
    resize(500, 400);

    // 设置默认值
    ui.lineEditBridgeName->setText("br0");
    ui.checkBoxStpEnabled->setChecked(true);
    ui.spinBoxStpPriority->setValue(32768);
    ui.spinBoxForwardDelay->setValue(15);
    ui.spinBoxHelloTime->setValue(2);
    ui.spinBoxMaxAge->setValue(20);

    // m_selectedDevices 由 setSelectedDevices 设置，构造时不赋值
    // 以第一个已选成员为基准网段
    QString baseIp, baseMask;
    for (const ConnectionInfo& conn : candidates) {
        if (m_selectedDevices.contains(conn.device)) {
            baseIp = conn.ipAddress;
            baseMask = conn.netmask;
            break;
        }
    }
    // 填充设备列表
    ui.listWidgetDevices->clear();
    for (const ConnectionInfo& conn : candidates) {
        QListWidgetItem *item = new QListWidgetItem(conn.device);
        item->setFlags(item->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
        if (m_selectedDevices.contains(conn.device)) {
            item->setCheckState(Qt::Checked);
        } else {
            item->setCheckState(Qt::Unchecked);
        }
        // 判断是否同网段
        if (!baseIp.isEmpty() && !isSameSubnet(baseIp, baseMask, conn.ipAddress, conn.netmask)) {
            item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
            item->setCheckState(Qt::Unchecked);
        }
        ui.listWidgetDevices->addItem(item);
    }
    // OK按钮校验
    connect(ui.buttonBox, &QDialogButtonBox::accepted, this, [this]() {
        int checkedCount = 0;
        for (int i = 0; i < ui.listWidgetDevices->count(); ++i) {
            QListWidgetItem* item = ui.listWidgetDevices->item(i);
            if ((item->flags() & Qt::ItemIsEnabled) && item->checkState() == Qt::Checked) {
                ++checkedCount;
            }
        }
        if (checkedCount < 2) {
            QMessageBox::warning(this, "输入错误", "桥接成员至少需要2个有效网卡");
            setResult(QDialog::Rejected);
            return;
        }
        accept();
    });
    connect(ui.buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}

BridgeConfigDialog::~BridgeConfigDialog() {}

QString BridgeConfigDialog::getBridgeName() const {
    return ui.lineEditBridgeName->text().trimmed();
}
QStringList BridgeConfigDialog::getSelectedDevices() const {
    // 修正：动态获取界面上勾选的设备
    QStringList checkedDevices;
    for (int i = 0; i < ui.listWidgetDevices->count(); ++i) {
        QListWidgetItem* item = ui.listWidgetDevices->item(i);
        if ((item->flags() & Qt::ItemIsEnabled) && item->checkState() == Qt::Checked) {
            checkedDevices << item->text();
        }
    }
    return checkedDevices;
}
bool BridgeConfigDialog::getStpEnabled() const {
    return ui.checkBoxStpEnabled->isChecked();
}
int BridgeConfigDialog::getStpPriority() const {
    return ui.spinBoxStpPriority->value();
}
int BridgeConfigDialog::getForwardDelay() const {
    return ui.spinBoxForwardDelay->value();
}
int BridgeConfigDialog::getHelloTime() const {
    return ui.spinBoxHelloTime->value();
}
int BridgeConfigDialog::getMaxAge() const {
    return ui.spinBoxMaxAge->value();
}

void BridgeConfigDialog::setBridgeName(const QString& name) {
    ui.lineEditBridgeName->setText(name);
}
void BridgeConfigDialog::setSelectedDevices(const QStringList& devices) {
    m_selectedDevices = devices;
    ui.listWidgetDevices->clear();
    for (const ConnectionInfo& conn : m_candidates) {
        QListWidgetItem *item = new QListWidgetItem(conn.device);
        // 调试输出
        fprintf(stderr, "[BridgeDebug] device=%s ip=%s mask=%s ",
            conn.device.toUtf8().constData(),
            conn.ipAddress.toUtf8().constData(),
            conn.netmask.toUtf8().constData());
        if (m_selectedDevices.contains(conn.device)) {
            fprintf(stderr, "已选成员, 可操作\n");
            item->setFlags(item->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
            item->setCheckState(Qt::Checked);
        } else {
            // 只要和br0同网段即可勾选
            bool canSelect = false;
            if (!m_bridgeIp.isEmpty() && !m_bridgeMask.isEmpty() && !conn.ipAddress.isEmpty() && !conn.netmask.isEmpty()) {
                if (isSameSubnet(m_bridgeIp, m_bridgeMask, conn.ipAddress, conn.netmask)) {
                    canSelect = true;
                }
            }
            if (canSelect) {
                fprintf(stderr, "同br0网段, 可选\n");
                item->setFlags(item->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
                item->setCheckState(Qt::Unchecked);
            } else {
                fprintf(stderr, "不同网段, 禁用\n");
                item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
                item->setCheckState(Qt::Unchecked);
            }
        }
        ui.listWidgetDevices->addItem(item);
    }
} 